<template>
  <el-dialog
    :visible.sync="show"
    custom-class="questionBankDialog"
    :before-close="handleClose"
    append-to-body
    :center="true"
    :close-on-click-modal="false"
  >
    <div class="iframeBox">
      <iframe
        :src="iframeRouter"
        width="100%"
        height="100%"
        frameborder="0"
        ref="iframeDom"
      ></iframe>
    </div>
  </el-dialog>
</template>

<script>
import { location_QuestionBank, location } from "@/util/tool";
import { Session } from '@/util/storage/session.js'
import { mapState } from "vuex";
export default {
  data() {
    return {
      show: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  props: {
    iframeShow: Boolean,
    iframeRouter: {
      type: String,
      default: function () {
        return `${location_QuestionBank(window)}/testlet/add`;
      },
    },
  },
  watch: {
    iframeShow(n, o) {
      this.show = n;
      if (n) {
        this.$nextTick(() => {
          this.listenIframeOnload();
        });
      }
    },
  },
  methods: {
    handleClose() {
      this.$emit("handleIframeClose");
    },
    /**
     * @description 监听iframe加载完成
     */
    listenIframeOnload() {
      const that = this;
      const iframe = this.$refs.iframeDom;
      // 处理兼容行问题
      if (iframe.attachEvent) {
        iframe.attachEvent("onload", function () {
          that.sendData(iframe);
          that.completeLoad = true;
        });
      } else {
        iframe.onload = function () {
          that.sendData(iframe);
          that.completeLoad = true;
        };
      }
    },
    /**
     * otherWindow.postMessage(message, targetOrigin, [transfer]);
     * https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
     * @description 向iframe发送消息
     */
    async sendData(dom) {
      let userInfoCookie = null;
      const res = await Session.get('userInfo', true)
      userInfoCookie = res;
      if (!userInfoCookie)
        return this.$antdMessage.error({
          content: "身份信息已过期！",
        });
      const params = {
        cookie: null,
        userInfo: this.userInfo,
        isStudy: false,
        iframeID: +new Date() + "" || "defaultIframeIDcreative",
      };
      dom.contentWindow.postMessage(JSON.stringify(params), location_QuestionBank(window))
      // dom.contentWindow.postMessage(JSON.stringify(params), "http://localhost:3000/");
      window.addEventListener(
        "message",
        (event) => {
          // Do we trust the sender of this message?  (might be
          // different from what we originally opened, for example).
          if (
            event.origin !== location(window) &&
            event.origin !== "http://localhost:3000"
          )
            return;
          const data = JSON.parse(event?.data);
          if (data.iframeID == params.iframeID) {
            this.$emit("createdTestlet", data.testLetData)
            this.show = false
            this.$emit("handleIframeClose");
          }
        },
        false
      );
    },
  },
};
</script>

<style lang="stylus">
.questionBankDialog {
  margin-top: 5vh !important;
  margin-bottom: 0 !important;
  width: 100%;
  max-width: 80%;
  min-width: 1200px;
  height: 100vh;
  max-height: 90vh;
  min-height: 700px;

  .el-dialog__header {
    padding: 0;
  }

  .el-dialog__body {
    padding: 0 !important;
    height: 100%;

    .iframeBox {
      width: 100%;
      height: 100%;
    }
  }
}
</style>